// pages/Pet/Subscribe/Subscribe.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryPetStore, queryPetInfo , queryPetProject , queryPetResercationTime } from '../../../api/pet';
import { submitPetServiceOrderForm } from '../../../api/petOrder';
import { queryAppInforMation } from '../../../api/brand';
import { formatTime } from '../../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    CustomBar: app.globalData.CustomBar,
    queryLongitude: wx.getStorageSync('longitude'),
    queryLatitude: wx.getStorageSync('latitude'),
    storeInfo: {
      'id': '',
      'name': '',
    },
    stroeId: '',
    petList: [], // 宠物列表
    petInfo: {},
    projectList: [], // 服务项目列表
    reservationDate: '', // 预约日期
    reservationTime: '', // 预约时间
    projectId: '',
    dateTimeList: [],
    showDate: false,
    currentDate: new Date().getTime(),
    minDate: new Date(2020,1,1).getTime(),
    maxDate: new Date().getTime(),
    safaBtm: wx.getSystemInfoSync().screenHeight - wx.getSystemInfoSync().safeArea.bottom,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this._queryPetStore();
    this._queryPetInfo();
    this._queryPetResercationTime();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    let userId = wx.getStorageSync('userId') ?? 10;
    return {
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  }, // 获取宠物门店
  _queryPetStore() {
    let _this = this;
    const {
      queryLongitude,
      queryLatitude,
      stroeId
    } = _this.data;
    queryPetStore({
        page: 0,
        size: 1,
        queryLongitude: queryLongitude,
        queryLatitude: queryLatitude,
        id: stroeId
      })
      .then(res => {
        if (res.success) {
          if (res.data.content.length > 0) {
            _this.setData({
              storeInfo: res.data.content[0],
            })
            _this._queryPetProject();
          }
        } else {
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
  },
  // 切换门店
  selStore() {
    let _this = this;
    wx.setStorageSync('selNearByStore', '1');
    wx.navigateTo({
      url: '/pages/Pet/NearByStore/NearByStore',
      events: {
        selStore: function (res) {
          _this.setData({
            stroeId: res.data,
          })
          _this._queryPetStore();
        }
      }
    })
  },
  // 查询宠物信息
  _queryPetInfo() {
    let _this = this;
    queryPetInfo({
        id: _this.data.petId,userId: wx.getStorageSync('userId')
      })
      .then(res => {
        if (res.success) {
          var list = [];
          for (let index = 0; index < res.data.content.length; index++) {
            const element = res.data.content[index];
            element.isPet = '1';
            list.push(element);
          }
          list.push({
            'isPet': '0',
          })
          _this.setData({
            petList: list,
            petInfo: res.data.content.length > 0 ? res.data.content[0] : {}
          })
          console.log(_this.data.petList, 'petList')
        } else {
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
  },
  // 切换选择宠物
  selPet(event) {
    const item = event.target.dataset.item || event.currentTarget.dataset.item;
    this.setData({
      petInfo: item,
    })
  },
  // 添加宠物
  addPet() {
    let _this = this;
    wx.navigateTo({
      url: '/pages/Users/AddPet/AddPet',
      events: {
        updatePetInfo: function (res) {
          _this._queryPetInfo();
        }
      }
    })
  },
  // 项目介绍
  toLink(e) {
    let _this = this;
    queryAppInforMation({infoType: '2',title: '项目介绍',page: 0})
    .then(res => {
      if (res.success) {
        if (res.data.content.length > 0) {
          var itm = res.data.content[0];
          if (res.data.content[0].imgUrl) {
            wx.navigateTo({
              url: `/pages/Link/LinkImg/LinkImg?url=${encodeURIComponent(itm.imgUrl)}&title=${JSON.stringify(item.label)}`,
            })
          } else if (itm.jumpUrl && itm.jumpUrl.length > 4 && itm.jumpUrl.substrin(0, 4) == 'http') {
            wx.navigateTo({
              url: `/pages/Link/Link/Link?url=${encodeURIComponent(itm.jumpUrl)}title=${JSON.stringify(item.label)}`,
            })
          } else if (res.data.content[0].content) {
            wx.navigateTo({
              url: `/pages/Link/LinkText/LinkText?content=${JSON.stringify(itm.content)}&title=${JSON.stringify(item.label)}`,
            })
          }
        } else {
          wx.showToast({
            title: '敬请期待',
            icon: 'none',
          })
        }
      } else {
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取服务项目信息
  _queryPetProject(){
    let _this = this;
    queryPetProject({})
    .then(res => {
      if(res.success){
        var proIdArr = _this.data.storeInfo.serviceProjectId.split(',');
        var list = [];
        for (let index = 0; index < res.data.content.length; index++) {
          const element = res.data.content[index];
          if(proIdArr.find(itm => itm.toString() == element.id.toString())){
            list.push(element);
          }
        }
        _this.setData({
          projectList: list,
          projectId: list.length > 0 ? list[0].id : '',
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 选择项目
  selProject(event){
    const item = event.target.dataset.item || event.currentTarget.dataset.item;
    this.setData({
      projectId: item.id,
    })
  },
  // 获取预约时间配置
  _queryPetResercationTime(){
    let _this = this;
    queryPetResercationTime({})
    .then(res => {
      if(res.success){
        _this.setData({
          dateTimeList: res.data.content,
        })
        _this.selDefaultDate();
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 展示时间选择器
  showDateEvent(){
    this.setData({
      showDate: true,
    })
  },
  onClose(){
    this.setData({
      showDate: false,
    })
  },
  // 确认选择时间
  dateConfirm(e){
    console.log(e.detail,'detail')
    var argumentTime = e.detail;
    // console.log(new Date(e.detail))
    var selDate = formatTime(e.detail,'Y-M-D');
    var now = new Date().getTime();
    var nowDate = formatTime(now,'Y-M-D');
    if(selDate == nowDate){
      argumentTime = now;
    }else{
      var argumentTime = new Date(`${selDate} 00:00:00`).getTime();
    }
    var selD = this.compulteDateTime(argumentTime);
    console.log(selD,'selD');
    this.setData({
      reservationDate: selD.reservationDate,
      reservationTime: selD.reservationTime,
      timeList: selD.timeList,
      showDate: false,
    })
  },
  // 选择预约日期
  selDefaultDate(){
    var selD = this.compulteDateTime();
    console.log(selD,'selD')
    var currentDate = new Date(selD.reservationDate).getTime();
    var minDate = currentDate;
    var maxDate = currentDate + 30 * 3600 * 24 * 1000;
    this.setData({
      reservationDate: selD.reservationDate,
      reservationTime: selD.reservationTime,
      currentDate: currentDate,
      minDate: minDate,
      maxDate: maxDate,
      timeList: selD.timeList,
    })
  },
  // 计算符合日期的时间段
  compulteDateTime(argTime){
    console.log(this.data.dateTimeList,'datetimelist')
    var nowDate = new Date();
    var nowHour = new Date().getHours() + 2;
    if(argTime){
      nowHour = new Date(argTime).getHours() + 2;
      nowDate = new Date(argTime);
    }
    console.log(nowHour,'nowHour')
    var reservationDate = formatTime(nowDate.getTime(),'Y-M-D'); // 预约日期
    var reservationTime = ''; // 预约时间
    var dateTimeList = this.data.dateTimeList;
    var minTime = 24;
    var maxTime = 0;
    var minT = ''; // 最小时间段
    var maxT = ''; // 最大时间段
    var timeList = [];
    for (let index = 0; index < dateTimeList.length; index++) {
      var item = dateTimeList[index];
      var itemTime = item.reservationTime;
      console.log(item,'item')
      var itemArr = itemTime.split('-');
      var start = parseInt(itemArr[0].split(':')[0]);
      var end = parseInt(itemArr[1].split(':')[0])
      if(start < nowHour && nowHour < end || start == nowHour || end == nowHour){
        reservationTime = item;
      }
      if(minTime >= start){
        minTime = start;
        minT = item;
      }
      if(maxTime <= end){
        maxTime = end;
        maxT = item;
      }
      console.log(end,nowHour,'end,nowhour')
      if(end > nowHour){
        timeList.push(item);
      }
    }
    console.log(minTime,maxTime,'min,max')
    if(nowHour <= minTime){
      console.log('走了最小')
      var nowTime = nowDate.getTime();
      reservationDate = formatTime(nowTime,'Y-M-D');
      reservationTime = minT;
    }
    if(nowHour >= maxTime){
      console.log('走了最大')
      var nowTime = nowDate.getTime();
      reservationDate = formatTime((nowTime + 24 * 3600 * 1000),'Y-M-D');
      reservationTime = minT;
      timeList = dateTimeList;
    }
    console.log(reservationDate,'reservationDate');
    console.log(reservationTime,'reservationTime');
    var obj = {
      'reservationDate': reservationDate,
      'reservationTime': reservationTime,
      'timeList': timeList,
    }
    return obj;
  },
  // 选择预约时间
  selTime(event){
    const item = event.target.dataset.item || event.currentTarget.dataset.item;
    this.setData({
      reservationTime: item,
    })
  },
  // 预约下单
  submitOrder(){
    let _this = this;
    console.log(_this.data.petInfo.id,'petId');
    console.log(_this.data.storeInfo.id,'storeId');
    console.log(_this.data.projectId,'projectId');
    console.log(_this.data.reservationDate,'resetionDate');
    console.log(_this.data.reservationTime,'reservationTime');
    var reservationTime = `${_this.data.reservationDate} ${_this.data.reservationTime.reservationTime}`
    submitPetServiceOrderForm({storeId: _this.data.storeInfo.id,petId: _this.data.petInfo.id,serviceProjectId: _this.data.projectId,reservationTime: reservationTime})
    .then(res => {
      if(res.success){
        wx.navigateTo({
          url: `/pages/Order/SubscribeSuccess/SubscribeSuccess?type=0&orderCode=${res.data.orderCode}`,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
})